package uk.co.biggroup.lotto.syndicate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
//import android.widget.Toast;
import android.widget.Toast;

public class Welcome extends Activity {

	public static final String PREFS_NAME = "Settings";
	TextView welcome;
	TextView downloadinfo;
	TextView wrongtokeninfo;
	Button leave;
	Button scan;
	RelativeLayout buttonsLayout;
	ProgressBar load;
	public static int error;
	public static int exception;
	public static int exceptionReason;
	public static String token = "token";
	static int i;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);
		setTitle("");
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		String tokenCheck = settings.getString(token, "");
		Logh.i(tokenCheck);
		buttonsLayout = (RelativeLayout) this
				.findViewById(R.id.RelativeLayout03);
		welcome = (TextView) this.findViewById(R.id.welcomeinfo);
		downloadinfo = (TextView) this.findViewById(R.id.downloadinfo);
		wrongtokeninfo = (TextView) this.findViewById(R.id.wrongtokeninfo);
		load = (ProgressBar) this.findViewById(R.id.loadbar);
		leave = (Button) this.findViewById(R.id.leave);
		scan = (Button) this.findViewById(R.id.scan);
		downloadinfo.setVisibility(View.GONE);
		wrongtokeninfo.setVisibility(View.GONE);
		welcome.setVisibility(View.GONE);
		load.setVisibility(View.GONE);

		scan.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(
						"com.google.zxing.client.android.SCAN");
				intent.setPackage("com.google.zxing.client.android");
				intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
				startActivityForResult(intent, 0);
			}
		});
		Logh.i("100");
		leave.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		if (tokenCheck.length() != 0) {
			welcome.setVisibility(View.GONE);
			leave.setVisibility(View.GONE);
			wrongtokeninfo.setVisibility(View.GONE);
			scan.setVisibility(View.GONE);
			downloadinfo.setVisibility(View.VISIBLE);
			load.setVisibility(View.VISIBLE);
			Logh.i("101");
			new DownloadGroups().execute("");
		} else {
			Logh.i("102");
			welcome.setVisibility(View.VISIBLE);
		}

	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				String contents = intent.getStringExtra("SCAN_RESULT");
				String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

				SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putString(token, contents);
				editor.putString("code_format", format);
				editor.commit();

				welcome.setVisibility(View.GONE);
				leave.setVisibility(View.GONE);
				scan.setVisibility(View.GONE);

				load.setVisibility(View.VISIBLE);
				downloadinfo.setVisibility(View.VISIBLE);

				Toast.makeText(this, contents, Toast.LENGTH_LONG).show();
				Logh.i("103");
				new DownloadGroups().execute("");

			} else if (resultCode == RESULT_CANCELED) {
				 Toast.makeText(this, getString(R.string.not_token_text), Toast.LENGTH_LONG).show();
			}
		}
	}

	private class DownloadGroups extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			exception = 0;
			try {
				Logh.i("125");
				getHtml();
			} catch (ClientProtocolException e) {
				exception = 1;
				exceptionReason = 1;
				Logh.i("ClientProtocolException");
			} catch (IOException e) {
				exception = 1;
				exceptionReason = 2;
				Logh.i("IOException");
			} catch (XPatherException e) {
				exception = 1;
				exceptionReason = 1;
				Logh.i("XPatherException");
			} catch (ParserConfigurationException e) {
				exception = 1;
				exceptionReason = 1;
				Logh.i("ParserConfigurationException");
			} catch (SAXException e) {
				exception = 1;
				exceptionReason = 1;
				Logh.i("SAXException");
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			if (exception == 1) {
				if (exceptionReason == 1) {
					wrongtokeninfo.setText(getString(R.string.error01_text));
				} else if (exceptionReason == 2) {
					wrongtokeninfo
							.setText(getString(R.string.need_internet_text));
				}
				buttonsLayout.setVisibility(View.GONE);
				downloadinfo.setVisibility(View.GONE);
				welcome.setVisibility(View.GONE);
				load.setVisibility(View.GONE);
				leave.setVisibility(View.GONE);
				scan.setVisibility(View.GONE);
				wrongtokeninfo.setVisibility(View.VISIBLE);

			} else {
				if (error == 1) {
					load.setProgress(80);
					downloadinfo.setVisibility(View.GONE);
					welcome.setVisibility(View.GONE);
					load.setVisibility(View.GONE);
					leave.setVisibility(View.VISIBLE);
					scan.setVisibility(View.VISIBLE);
					wrongtokeninfo.setVisibility(View.VISIBLE);
				} else {
					load.setProgress(100);

					wrongtokeninfo.setVisibility(View.GONE);
					// !!!!!!HERE GO TO FIRST ACTIVITY
					Intent intent = new Intent();
					intent.setClass(Welcome.this, Draws.class);
					startActivity(intent);
					finish();

				}
			}
		}

		@Override
		protected void onPreExecute() {
			load.setProgress(40);
			// dialog = ProgressDialog.show(Welcome.this, "",
			// "Wait, Accessing data...", true);
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// mProgressDialog.setProgress(args[0]);

		}
	//	XPatherException,
		public void getHtml() throws ClientProtocolException, IOException,
				 ParserConfigurationException, SAXException,
				IOException, XPatherException {
			Logh.i("130");
			String ERROR_XPATH = "//error/@msg";

			TagNode node;

			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			String tokenCheck = settings.getString(token, "");
			Logh.i("http://syndicates.biggroup.co.uk/MyAccount/DownloadXML.aspx?t=" + tokenCheck);
			URL url = new URL(
					"http://syndicates.biggroup.co.uk/MyAccount/DownloadXML.aspx?t="
							+ tokenCheck);
			URLConnection conn = url.openConnection();

			HtmlCleaner cleaner = new HtmlCleaner();
			CleanerProperties props = cleaner.getProperties();
			props.setAllowHtmlInsideAttributes(true);
			props.setAllowMultiWordAttributes(true);
			props.setRecognizeUnicodeChars(true);
			props.setTranslateSpecialEntities(true);
			props.setOmitComments(true);

			node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
			Object[] error_nodes = node.evaluateXPath(ERROR_XPATH);
			error = 0;
			if (error_nodes.length > 0) {
				for (Object linkNode : error_nodes) {
					String s = linkNode.toString();
					error = 1;
					Logh.i("SYNDICATE ERROR: " + s);
				}
			}

		}
	}

}
